from server_send_and_receive_test import *
from game import *
from player import *
from time import sleep
import sys
from socket import *
import thread

#start connection
port=12345
broadport=52133
if len(sys.argv)>1:
    port=int(sys.argv[1])

pipe=ServerPipe("",port)
pipe.startConnection()

ip = "127.0.0.1" #"10.16.1.90"

#Broadcasting function so clients can find game
def broadcastServer(ip,broadport):

    
    s = socket(AF_INET, SOCK_DGRAM)
    s.bind((ip,broadport))
    s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)

    while 1:
        data = "DRAZAH: %s:%s"%(ip,port)
        s.sendto(data,("<broadcast>", broadport))
        time.sleep(2)

thread.start_new_thread(broadcastServer,(ip,broadport))

games=[]
playersWaiting=[]



while True:
    
    if pipe.connections.qsize()>0:
        con=pipe.connections.get()
        player=Player()
        player.setConnection(con)
        player.score=0
        playersWaiting.append(player)
    while len(playersWaiting)>=2:
        g=Game()

        g.stateStep()
        g.playerList.append(playersWaiting[0])
        g.playerList.append(playersWaiting[1])
        games.append(g)
        del playersWaiting[0:2]
    for g in games:
        err=False
        #print "0:",g.playerList[0].connection.fileno()
        #print "1:",g.playerList[1].connection.fileno()
        try:
            g.stateStep()
        except error:
            print "Player has disconnected"
            err=True
        #    g.playerList[0].connection
        if err:
            for i in g.playerList:
                try:
                    i.connection.sendall("")
                except error:
                    g.playerList.remove(i)
            
            for i in g.playerList:
                i.connection.sendall("RESET:The other player disconnected.\n")
                i.newGameReset()
                playersWaiting.append(i)
                #g.playerList.remove(i)
            g.state="DELETE"
        #g.stateStep()
        playersWaiting.extend(g.recycle)
        g.recycle=[]
        if g.state=="DELETE":
            games.remove(g)
    sleep(0.5)

#  LocalWords:  playersWaiting del broadcastServer ip DRAZAH ServerPipe len
#  LocalWords:  startConnection broadport argv setsockopt sendto playerList
#  LocalWords:  sendall
